package com.masz.seataone.service;

import com.alibaba.fastjson.JSONObject;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.LocalTCC;
import io.seata.rm.tcc.api.TwoPhaseBusinessAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author masz
 * @Date 2022/2/14 15:21
 * seata tcc
 */
@Service
public class SeataOneTccService implements SeataOneTccServiceIntf {

    @Autowired
    RestTemplate restTemplate;

    @Transactional(rollbackFor = Exception.class)
    public void tcc(String t) {
        System.out.println("tcc one "+t);
        rpcTccTwo("c");
//        rpcTccThree(t);
    }

    public boolean commit(BusinessActionContext businessActionContext) {
        Map<String, Object> actionContext = businessActionContext.getActionContext();
        System.out.println("commit tcc one ");
        return true;
    }

    public boolean rollback(BusinessActionContext businessActionContext) {
        Map<String, Object> actionContext = businessActionContext.getActionContext();
        System.out.println("rollback tcc one ");
        return true;
    }


    public void rpcTccTwo(String v) {
        JSONObject date = new JSONObject();
        date.put("v", v + "-two");
        restTemplate.postForEntity("http://seata-two/seata/tcc", date, String.class);
    }

    public void rpcTccThree(String v) {
        JSONObject date = new JSONObject();
        date.put("v", v + "-three");
        restTemplate.postForEntity("http://seata-three/seata/tcc", date, String.class);
    }

}
